import os
import fitz
import re
from PIL import Image

ptn = r'\d{4}/\d{2}/\d{2}|\d{2}:\d{2}'

def image_from_pdf(input_pdf, output_folder):
    pdf_size = os.path.getsize(input_pdf)
    if pdf_size < 1000:
        print(f'pdf_size:[{pdf_size}]', input_pdf)
        return 0
    
    pid = input_pdf.split('/')[-2]
    patient_folder = os.path.join('/rdfs/data/ECG/ECG_301/sorted/', pid)
    print(patient_folder)
    doc = fitz.open(input_pdf)
    for page_num in range(len(doc)):
        page = doc[page_num]
        text_instances = page.get_text('dict')['blocks']
        uid_ts = ''
        for instance in text_instances:
            if 'lines' in instance:
                for insl in instance['lines']:
                    text_ele = [lt['text'] for lt in insl['spans']]
                    
                    if '编号:' in text_ele[0]:
                        uid = text_ele[0]
                    if '检查日期' in text_ele[0]:
                        match = re.search(ptn, text_ele[0])
                        if match:
                            ts = match.group()
                    a, b, c, d = instance['bbox']
                    remove_box = True
                    if a >= 200 and a <= 540:
                        remove_box = False
                    if remove_box:
                        rect = fitz.Rect(instance['bbox'])
                        page.add_redact_annot(rect)
        
        if uid[0] == '空' or uid[0] == '同':
            print(uid, input_pdf)
        page.apply_redactions()
        img_list = page.get_images()
        if len(img_list) > 0:
            for img in img_list:
                page.delete_image(img[0])
        pix = page.get_pixmap(dpi=500)
        output_image = f'{output_folder}/{uid.replace("编号:", "")}_{ts.replace("/", "-").replace("  ", "_").replace(" ", "")}.png'
        pix.save(output_image)
        svg = page.get_svg_image()
        with open() as svg_file:
            svg_file.write(svg)
        doc.close()

def parse_d(d):
    cur_mode = ''
    cur_pos = (0, 0)
    path = []
    buffer = ''
    for c in d:
        if c not in '0123456789':
            if len(buffer) > 0:
                pos_list = [int(i) for i in buffer.split(' ')]
                if cur_mode in ['M', 'L']:
                    pos_list = [(pos_list[i], pos_list[i+1]) for i in range(0, len(pos_list), 2)]
                if cur_mode == 'H':
                    pos_list = [(i, path[-1][1]) for i in pos_list]
                buffer = ''
                path.extend(pos_list)
            cur_mode = c
        else:
            buffer += c
    return path


def svg2csv(fpath):
    with open(fpath, 'r') as f:
        svg_content = f.read()
    root = ET.fromstring(svg_content)
    pdd = [path.get('d') for path in root.findall('.//{http://www.w3.org/2000/svg}path')]
    line_idx = 0
    data_dict = {}
    max_len = 0
    for i, d in enumerate(pdd):
        if len(d) > 10000:
            path = parse_d(d)
            x, y = zip(*path)
            data_dict[f'x{line_idx}'] = list(x)
            data_dict[f'y{line_idx}'] = list(y)
            line_idx += 1
            max_len = max(max_len, len(x))
    for k, v in data_dict.items():
        data_dict[k] = v + [-1] * (max_len - len(v))
    df = pd.DataFrame(data_dict)
    outpath = fpath.replace('svg', 'csv')
    df.to_csv(outpath, index=False)
    return 0
